import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Django.settings")
import django
django.setup()
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
import logging
logging.basicConfig(level=logging.INFO)
from sm_system.models import *
from salesRecord.views import record_list
from customer.views import index as customer_index
from commodity.views import commodity_info
from tools import encrypt_md5, id_generate
# Create your views here.



BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
COOKIE_NAME = 'sm_session'


def index(request):

    id = request.COOKIES.get(COOKIE_NAME)
    if not id:
        user = ''
    else:
        user = ClerkInfo.objects.get(id=id).name
    return render(request, 'index_sm.html', {'user': user})


def login(request):

    return render(request, 'login_sm.html')


def authenticate(request):

    id = request.POST.get('id')
    password = request.POST.get('password')

    content = {'message': '', 'user': None}
    try:
        clerk_info = ClerkInfo.objects.get(id=id)
    except Exception as e:
        logging.info(e)
        content['message'] = '该用户不存在！'
        return JsonResponse(content)

    if encrypt_md5(password) == clerk_info.password:
        content['user'] = clerk_info.name
        res = JsonResponse(content)
        res.set_cookie(COOKIE_NAME, clerk_info.id, max_age=86400, httponly=True)
        return res
    else:
        content['message'] = '输入的信息有误！'
        return JsonResponse(content)


def logout(request):

    rep = redirect("/sm_system/login/")
    rep.delete_cookie(COOKIE_NAME)  # 删除用户浏览器上之前设置的cookie值
    return rep


def identification(request):

    clerk_id = request.COOKIES.get(COOKIE_NAME)
    if not clerk_id:
        return False
    else:
        return True


# 查询销售记录
def view_salesRecord(request):

    if not identification(request):
        return redirect('/sm_system/login/')
    else:
        clerk_id = request.COOKIES.get(COOKIE_NAME)
        supermarket_id = ClerkInfo.objects.get(id=clerk_id).supermarket_id
        return record_list(request, supermarket_id)


# 查询会员明细
def customer_info(request):

    if not identification(request):
        return redirect('/sm_system/login/')
    else:
        return customer_index(request)


# 会员编号生成
def customer_id(request):

    flag = True
    while flag:
        temp_id = id_generate(how_many=1, length=11)[0]
        try:
            CustomerInfo.objects.get(id=temp_id)
        except Exception as e:
            logging.info(e)
            only_id = temp_id
            flag = False
    context = {'customer_id': str(only_id)}
    return JsonResponse(context)


# 显示商品信息
def view_commodity(request):

    if not identification(request):
        return redirect('/sm_system/login/')
    else:
        clerk_id = request.COOKIES.get(COOKIE_NAME)
        supermarket_id = ClerkInfo.objects.get(id=clerk_id).supermarket_id
        return commodity_info(request, supermarket_id)


# 商品编号生成
def commodity_id(request):

    flag = True
    while flag:
        temp_id = id_generate(how_many=1, length=11)[0]
        try:
            CommodityInfo.objects.get(id=temp_id)
        except Exception as e:
            logging.info(e)
            only_id = temp_id
            flag = False
    context = {'commodity_id': str(only_id)}
    return JsonResponse(context)


if __name__ == '__main__':

    # authenticate('00021352647', '123456')
    pass
